#little set of helper functions for zip files

#from __future__ import with_statement - ZipFile objects do NOT have any __exit__ function.

import os
import zipfile
import cStringIO #it's faster than StringIO, but it will be removed in python 3k

def get_file(zip, n):
    zip = zipfile.ZipFile(zip, 'r')
    value = zip.read(zip.namelist()[n])
    zip.close()
    return cStringIO.StringIO(value)

def listdir(path):
    """an implementation of os.listdir that works also
    on zipfiles"""
    if os.path.exists(path):
        if os.path.isdir(path):
            return os.listdir(path)
        if os.path.splitext(path)[1] == '.zip': #path points to a zip
            arc = zipfile.ZipFile(path, 'r')
            return arc.namelist()
    else:
        raise OSError("%s does not exists" %path)

def isfile(path):
    p_path = path.split(':')[0]
    name, ext = os.path.splitext(p_path)
    if ext == '.zip':
        return path.split(':')[1] in listdir(p_path)
    else:
        return os.path.isfile(path)

def save_file(zip, name, value):
    if os.path.isfile(zip):
        zip = zipfile.ZipFile(zip, 'a')
    else:
        zip = zipfile.ZipFile(zip, 'w')
    zip.writestr(name, value)
    zip.close()